package com.zrwl.poscloud.xo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrwl.poscloud.commons.config.message.SmsConfig;
import com.zrwl.poscloud.commons.vo.message.SmsVO;
import com.zrwl.poscloud.xo.service.SmsService;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    SmsConfig smsConfig;
    @Override
    public String queryAccount() throws Exception {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(smsConfig.getQueryUrl());
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());

        NameValuePair[] data = {
                new NameValuePair("accesskey", smsConfig.getAccesskey()),
                new NameValuePair("secret", smsConfig.getAccessSecret())
        };
        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(postMethod);
        return "{statusCode: " + statusCode + ", body: " + postMethod.getResponseBodyAsString() + "}";
    }

    @Override
    public SmsVO send(String mobile, String templateId, String content) throws IOException {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(smsConfig.getSendUrl());
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        SmsVO smsVO = new SmsVO();
//        String content = keywords.stream().map(String::valueOf).collect(Collectors.joining(SMS_SEPARATE));

        NameValuePair[] data = {
                new NameValuePair("accesskey", smsConfig.getAccesskey()),
                new NameValuePair("secret", smsConfig.getAccessSecret()),
                new NameValuePair("sign", "【" + smsConfig.getSign() + "】"),
                new NameValuePair("templateId", templateId),//
                new NameValuePair("mobile", mobile),
//                new NameValuePair("content", URLEncoder.encode("先生##9:40##快递公司##1234567", "utf-8"))//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
                new NameValuePair("content", URLEncoder.encode(content, "utf-8"))//（示例模板：{1}您好，您的订单于{2}已通过{3}发货，运单号{4}）
        };
        postMethod.setRequestBody(data);
        postMethod.setRequestHeader("Connection", "close");
        int statusCode = httpClient.executeMethod(postMethod);
        if (statusCode != 200) {
            smsVO.setRequestSuccess(false);
            smsVO.setCode("HttpError" + statusCode);
            smsVO.setMsg("Http请求失败：" + statusCode);
        } else {
            smsVO.setRequestSuccess(true);
            JSONObject result = JSON.parseObject(postMethod.getResponseBodyAsString());
            smsVO.setCode(result.getString("code"));
            smsVO.setMsg(result.getString("msg"));
            if ("0".equals(result.getString("code")))
                smsVO.setSendSuccess(true);
            else
                smsVO.setSendSuccess(false);
        }
        return smsVO;
    }
}
